package rpc.frame.client.discovery.zk;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import rpc.frame.client.cache.local.DefaultServiceProviderCache;
import rpc.frame.client.discovery.RpcServiceDiscovery;
import rpc.frame.core.provider.ServiceProvider;

import javax.annotation.Resource;
import java.util.List;

@Component
@Slf4j
public class ZkServiceDiscovery implements RpcServiceDiscovery {

    @Resource
    private ClientZKit clientZKit;

    @Resource
    private DefaultServiceProviderCache cache;

    /**
     * 获取注册注册中心全量的 注册信息
     * 监听 serviceName
     */
    @Override
    public void serviceDiscovery() {
        List<String> serviceList = clientZKit.getServiceList();
        if(!CollectionUtils.isEmpty(serviceList)){
            for(String serviceName:serviceList){
                //获取 接口下的服务它提供在存储到缓存中
                List<ServiceProvider> serviceInfos = clientZKit.getServiceInfos(serviceName);
                cache.put(serviceName,serviceInfos);
                log.info("订阅的接口{},提供者有{}",serviceName,serviceInfos);
                //添加监听
                clientZKit.subscribeZkEvent(serviceName);
            }
        }


    }
}
